package sz.szsmk.citizencard.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.baidu.android.pushservice.BasicPushNotificationBuilder;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.target.ViewTarget;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;

import java.util.List;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.LoadingActivityBinding;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.model.network.bean.JumpActivityBean;
import sz.szsmk.citizencard.model.network.bean.response.QueryMainAdRes;
import sz.szsmk.citizencard.model.network.bean.response.TagConfigRes;
import sz.szsmk.citizencard.mvp.contract.ILodingContact;
import sz.szsmk.citizencard.mvp.presenter.LoadingPresenter;
import sz.szsmk.citizencard.ui.adapter.LoadingPageAdapter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.ui.dialogs.PolicyDialog;
import sz.szsmk.citizencard.ui.dialogs.PrivacyPolicyDlg;
import sz.szsmk.citizencard.ui.dialogs.ShowADDialog;
import sz.szsmk.citizencard.ui.fragment.ElecCardSignDialog;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.AnimationsContainer;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpThirdView;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.SecureSharedPreferences;
import sz.szsmk.citizencard.util.SharedPreferencesTool;
import sz.szsmk.citizencard.widget.CircleProgressbar;
import sz.szsmk.citizencard.widget.PureTextWebViewActivity;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/8/27 14:13
 * description:
 */
public class LoadingActivity extends IBaseActivity<LoadingPresenter, LoadingActivityBinding>
        implements ILodingContact.ILodingView, CircleProgressbar.OnCountdownProgressListener, View.OnClickListener, ViewPager.OnPageChangeListener {

    private boolean isNotFirstOpen;
    private int[] imgList;
    private LoadingPageAdapter loadingPageAdapter;
    private boolean isAdClick;//是否是点击跳过
    private Button loadJump;
    private boolean isJumpMain = false;
    private RelativeLayout loadLogo;

    private final int REQ_CODE_POLICE_ACT = 10001;

    @Override
    protected int attachLayoutRes() {
        return R.layout.loading_activity;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initSystemBar() {
        ImmersionBar.with(this).init();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void onDestroy() {
        if(downTimer!=null){
            downTimer.cancel();
        }
        super.onDestroy();
    }


    @Override
    protected void initViews() {
        if (SecureSharedPreferences.getBoolean("pilicyDialog",true)){
            Intent intent = new Intent(LoadingActivity.this, PolicyTranslateActivity.class);
            startActivityForResult(intent, REQ_CODE_POLICE_ACT);
        } else {
            nextStep();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REQ_CODE_POLICE_ACT) {
            if(resultCode==RESULT_OK) {
                nextStep();
            } else {
                finish();
            }
        }
    }

    private void nextStep() {

        mPresenter.queryMainAd();
        mPresenter.userBehaviorActivity();
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                //        推送
                PushManager.startWork(LoadingActivity.this, PushConstants.LOGIN_TYPE_API_KEY,
                        "pkSH7agKcpGWH4UsOie8va3W");
                // 1.默认通知
                // 若您的应用需要适配Android O（8.x）系统，且将目标版本targetSdkVersion设置为26及以上时：
                // SDK提供设置Android O（8.x）新特性---通知渠道的设置接口。
                // 若不额外设置，SDK将使用渠道名默认值"Push"；您也可以仿照以下3行代码自定义channelId/channelName。
                // 注：非targetSdkVersion 26的应用无需以下调用且不会生效
                BasicPushNotificationBuilder bBuilder = new BasicPushNotificationBuilder();
                bBuilder.setChannelId("testDefaultChannelId");
                bBuilder.setChannelName("testDefaultChannelName");
                PushManager.setDefaultNotificationBuilder(LoadingActivity.this, bBuilder); //使自定义channel生效

            }
        });

        dataBinding.loadingWelcomeImg.setOnClickListener(this);
        loadJump = dataBinding.loadJump;
        loadLogo = dataBinding.loadLogo;
        dataBinding.loadJump.setOnClickListener(this);
        dataBinding.welGuideViewpager.setOnClickListener(this);
        dataBinding.welGuideViewpager.addOnPageChangeListener(this);
        dataBinding.startHomeIv.setOnClickListener(this);
        dataBinding.rlInfo.setVisibility(View.GONE);
        //每次从闪屏页进入APP的时候清除协议版本数据 在主页重新获取协议数据 避免多次请求造成的服务器压力
        ACache.get(DaggerApplication.getIns()).remove("protocolVersion");
    }

    private int[] getRes(int res) {
        TypedArray typedArray = getResources().obtainTypedArray(res);
        int len = typedArray.length();
        int[] resId = new int[len];
        for (int i = 0; i < len; i++) {
            resId[i] = typedArray.getResourceId(i, -1);
        }
        typedArray.recycle();
        return resId;
    }
    private void setWelViewVisible(boolean isVisible) {
        dataBinding.welGuideViewpager.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    private Handler handler = new Handler();
    MyCountDownTimer downTimer;
    private void loadingWelcome() {

        loadJump.setVisibility(View.VISIBLE);
        //loadLogo.setVisibility(View.VISIBLE);
        downTimer  = new MyCountDownTimer(5000+500, 1000);
        downTimer.start();


        if (!TextUtils.isEmpty(resource_url)) {
            Log.i("resource_url", resource_url);
            if (!isDestroyed(this)) {
                Glide.with(this).load(resource_url).into(dataBinding.loadingWelcomeImg);
            }
        }else{
            downTimer.cancel();
            startToHomeActivity();
        }

        setWelViewVisible(false);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if(position==3){
            dataBinding.startHomeIv.setVisibility(View.VISIBLE);

        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    class MyCountDownTimer extends CountDownTimer {
        /**
         * @param millisInFuture    表示以毫秒为单位 倒计时的总数
         *                          <p>
         *                          例如 millisInFuture=1000 表示1秒
         * @param countDownInterval 表示 间隔 多少微秒 调用一次 onTick 方法
         *                          <p>
         *                          例如: countDownInterval =1000 ; 表示每1000毫秒调用一次onTick()
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        public void onFinish() {
            startToHomeActivity();
        }

        public void onTick(long millisUntilFinished) {
            loadJump.setText("跳过" + millisUntilFinished / 1000 + "s");
        }
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void onProgress(int what, int progress) {
        if (what == 1 && progress == 100 && !isAdClick) {
            isAdClick = true;
//            startToHomeActivity();
        }
    }

    private void startToHomeActivity() {
        Bundle bundle = null;
        if(getIntent().getData()!=null) {
            bundle = new Bundle();
            Uri uri = getIntent().getData();
            if (uri != null) {
                try {
                    JumpActivityBean jumpActivityBean = new Gson().fromJson(uri.getQueryParameter("data"), JumpActivityBean.class);
                    bundle.putSerializable("jumpActivityBean",jumpActivityBean);

                } catch (Exception e) {
                }
            }
        }else {
        //正常启动带参数，NFC刷卡启动不带参数
            bundle=new Bundle();
            bundle.putString("nfc","nodata");
        }

        JumpUtils.jumptoNatvie(this, "main", 0,bundle);
        finish();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.loading_welcome_img) {
            JumpThirdView.baseToJumpView(this, link_url, sys_label, need_header, "");

            mPresenter.userBehaviorBrowse(44);

            finish();
        } else if (id == R.id.wel_guide_viewpager) {
        } else if (id == R.id.start_home_iv) {//点击之后存储状态下次进来判断是否是第一次打开客户端
            SharedPreferencesTool.saveBoolean(this, "isNotFirstOpen", true);
            //点击跳转欢迎页
            loadingWelcome();
        } else if (id == R.id.load_jump) {
            startToHomeActivity();
        }
    }
    QueryMainAdRes.MainAdListBean mainAdListBean;
    private String link_url="";
    private String resource_url="";
    private int need_header;
    private String sys_label;
    @Override
    public void queryMainAdSucc(QueryMainAdRes splashResponse) {
        if(splashResponse.getMain_ad_list()!=null && splashResponse.getMain_ad_list().size()>0){
            mainAdListBean = splashResponse.getMain_ad_list().get(0);
            resource_url = mainAdListBean.getResource_url();
            link_url = mainAdListBean.getLink_url();
            need_header = mainAdListBean.getNeed_header();
            sys_label = mainAdListBean.getSys_label();
        }
    }

    @Override
    public void queryMainAdFail(QueryMainAdRes response) {
        if (response.getMain_ad_list() != null && response.getMain_ad_list().size() > 0) {
            QueryMainAdRes.MainAdListBean mainAdListBean = response.getMain_ad_list().get(0);
            String link_url = mainAdListBean.getResource_url();
            if (!TextUtils.isEmpty(link_url)) {
                Glide.with(this).load(link_url).into(dataBinding.loadingWelcomeImg);
            }
        }
    }

    public boolean isDestroyed(Activity mActivity) {
        if (mActivity == null || mActivity.isFinishing() || Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1
                && mActivity.isDestroyed()) {
            return true;
        } else {
            return false;
        }
    }

}